#!/bin/bash
_script_dir=`dirname $0`
_meta_ivi=`dirname ${_script_dir}`

_check_it=`basename ${_meta_ivi}`
if [ "x${_check_it}" != "xmeta-ivi" ]; then
   echo "this is not script of meta-ivi"
   exit 1
fi
_top_dir=`dirname ${_meta_ivi}`

_build=${_top_dir}/build
_machine='qemux86-64'
_image=`grep bitbake ${_meta_ivi}/README.md | awk '{print $4}'`
while getopts "hm:i:b:" arg; do
  case $arg in
    h)
      echo "usage $0 [option] [runqemu option]" 
      echo "  -h        display this message"
      echo "  -m        set machine"
      echo "  -i        set image name"
      echo "  -b        set build directory"
      exit 0
      ;;
    m)
      _machine=$OPTARG
      ;;
    i)
      _image=${OPTARG}-image
      ;;
    b)
      _build=${_top_dir}/$OPTARG
      ;;
  esac
done
shift $((OPTIND-1))

w_bit=`which bitbake`
if [ "x${w_bit}" == "x" ]; then
   export TEMPLATECONF=${_meta_ivi}/meta-ivi/conf
   _poky=${_top_dir}/poky
   source ${_poky}/oe-init-build-env ${_build}
else
   cd ${_build}
fi

_DIR=tmp/deploy/images/${_machine}
_CONF=${_DIR}/${_image}-${_machine}.qemuboot.conf
_ARG=""
if [ -e ${_CONF} ]; then
   _ARG=${_CONF}
else
   _K=${_DIR}/*-${_machine}.bin
   _I=${_DIR}/${_image}-${_machine}.ext*
   if [ -e ${_K} -a -e ${_I} ]; then
      _k=`\ls ${_DIR}/*-${_machine}.bin`
      _i=`\ls ${_DIR}/${_image}-${_machine}.ext*`
      if [ "${_machine}" == "vexpressa9" ]; then
         _ARG="vexpress-a9 ${_k} ${_i}"
      else
         _ARG="${_machine} ${_k} ${_i}"
      fi
   else
      if [ ! -e ${_K} ]; then
         echo there is no ${_K}
      fi
      if [ ! -e ${_I} ]; then
         echo there is no ${_I}
      fi
      exit 2
   fi
fi
../poky/scripts/runqemu ${_ARG} $*
